using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
using System.IO;

using MiniJSONx;

public class SpeakerEditor : EditorWindow {
	
	static List<NAID_Data.DialogueSpeaker> MySpeakers = new List<NAID_Data.DialogueSpeaker>();
	
	static string SpeakerJSON = Application.dataPath + "/NAID/Resources/NAID Resources/VNSpeakers.txt";
	NAID_Data.DialogueSpeaker CurrentSpeaker = null;
	
	void OnGUI()
	{
		GUILayout.BeginHorizontal();
			if(GUILayout.Button("New Speaker"))
			{
				MySpeakers.Add(new NAID_Data.DialogueSpeaker());
				CurrentSpeaker = MySpeakers[MySpeakers.Count - 1];
			}
		
			if(GUILayout.Button("Save"))
			{
				WriteJSON();
			}
		GUILayout.EndHorizontal();
		GUILayout.BeginVertical();
		
		if(CurrentSpeaker != null)
		{
			CurrentSpeaker.DisplayName = GUILayout.TextField(CurrentSpeaker.DisplayName);
			CurrentSpeaker.FullName = GUILayout.TextField(CurrentSpeaker.FullName);
			CurrentSpeaker.TextColor = EditorGUILayout.ColorField(CurrentSpeaker.TextColor);
		}
		
		GUILayout.EndVertical();
	}
	
	void WriteJSON()
	{
		Debug.Log("Writing JSON");
		
		StreamWriter wr = new StreamWriter(SpeakerJSON);
		
		wr.WriteLine("{");
		
		wr.WriteLine("\t\"Speakers\" : [");
		for(int i = 0; i < MySpeakers.Count; i++)
		{
			wr.WriteLine("\t\t{");
			wr.WriteLine("\t\t\"id\" : " + "\"" + i.ToString() + "\",");
			wr.WriteLine("\t\t\"FullName\" : " + "\"" + MySpeakers[i].FullName + "\",");
			wr.WriteLine("\t\t\"DisplayName\" : " + "\"" + MySpeakers[i].DisplayName + "\",");
			wr.WriteLine("\t\t\"TextColor\" : [");
			
			wr.WriteLine("\t\t\t\"" +MySpeakers[i].TextColor.r.ToString() + "\",");
			wr.WriteLine("\t\t\t\"" +MySpeakers[i].TextColor.g.ToString() + "\",");
			wr.WriteLine("\t\t\t\"" +MySpeakers[i].TextColor.b.ToString() + "\",");
			wr.WriteLine("\t\t\t\"" +MySpeakers[i].TextColor.a.ToString() + "\"");
			
			wr.WriteLine("\t\t]");
			wr.Write("\t\t}");
			
			if(i != MySpeakers.Count -1)
				wr.Write(",\n");
			else
				wr.Write("\n");
		}
		wr.WriteLine("\t]");
		
		wr.WriteLine("}");
		
		wr.Close();
		
		Debug.Log("Saved " + SpeakerJSON);
	}
	
	static void ParseJSON()
	{
		
	}
	
	[MenuItem("NAID/Speaker Editor")]
	public static void Init()
	{
		Debug.Log(SpeakerJSON);
		
		if(!File.Exists(SpeakerJSON))
		{
			StreamWriter newWr = new StreamWriter(SpeakerJSON);
			newWr.Close();
			
			AssetDatabase.Refresh();
			
			Debug.Log("JSON File created at " + SpeakerJSON);
		}
		else
		{
			Debug.Log("Speaker file exists parsing " + SpeakerJSON);
			List<NAID_Data.DialogueSpeaker> spk =  NAID_JSONParser.ParseSpeakers();
			
			Debug.Log(spk[0].DisplayName);
		}
		
		SpeakerEditor win = (SpeakerEditor)EditorWindow.GetWindow(typeof(SpeakerEditor));
	}
}
